'use strict';
const {
	db_select
} = require('../../model/index.js')
const db = uniCloud.database();
const dbCmd = db.command
const $ = db.command.aggregate
const tools = require("../../tools/index.js")
const alioss = require('../../oss/index.js')


// 检查Token是否存在或过期
exports.APICheckToken = async (Token) => {
	// 查询数据
	let res = await db_select("User", {
		Token
	})
	if (res.data.length == 0 || res.data === null) {
		return {
			code: 211,
			msg: "Token已过期,请重新登录"
		}
	}
	// 数据存在
	if (res.data.length >= 1) {
		return {
			code: 200,
			msg: "身份校验通过",
			result: res
		}
	}
	return {
		msg: "内部错误~",
		code: 500
	}
}

// 检查版本更新
exports.CheckUpdate = async function(body_data) {
	let res = {
		code: 200,
		msg: "成功~"
	}
	let {
		Os
	} = body_data
	if (!Os) return {
		code: 200,
		msg: "参数错误~"
	}
	let result = await db.collection('adminVersion').where({
		Os,
		IsCurrentUse: true
	}).get()
	if (result.requestId) {
		let url = alioss.client.signatureUrl(result.data[0].DownUrl, {
			expires: 3600
		});
		result.data[0].DownUrl = url
		res.msg = '查询成功~'
		res.data = result.data[0]
	} else {
		res.msg = '内部错误~'
	}
	return res
}

// 检查所有历史更新版本
exports.SelUpdateList = async function(body_data) {
	let {
		UserInfo,
		pageNum,
		pageSize
	} = body_data
	if (!pageSize) return {
		code: 204,
		msg: "参数错误"
	}
	let skips = pageNum * pageSize
	let res = {
		code: 200,
		msg: "查询成功~"
	}
	let result = await db.collection('adminVersion').orderBy('createTime', 'desc').limit(pageSize).skip(skips).get()
	let total = await db.collection('adminVersion').count()
	res.data = result.data
	res.total = total.total
	return res
}

// 获取最新版本的更新包
exports.SelNewApk = async function(body_data) {
	let returnData = {
		code: 200,
		msg: "参数错误~"
	}
	let {
		Os
	} = body_data
	if (!Os) return returnData
	
	let result = await db.collection('adminVersion').where({
		Os,
		DownUrl:/\.(apk)$/g
	}).orderBy('createTime', 'desc').get()
	
	if (result.requestId) {
		let url = alioss.client.signatureUrl(result.data[0].DownUrl, {
			expires: 3600
		});
		result.data[0].DownUrl = url
		returnData.msg = '查询成功~'
		returnData.data = result.data[0]
	} else {
		returnData.code = 500
		returnData.msg = '内部错误~'
	}
	return returnData
}